<template>
  <div class="book-container">
    <Row class="margin-top-10">
      <i-col span="24">
        <Card>
          <p class="title" slot="title">
            书籍管理
            <Button
              class="add-icon"
              type="primary"
              icon="android-add"
              @click="handleAdd"
            >
              新增书籍
            </Button>
            <Button
              class="sync-btn"
              type="warning"
              @click="updateBookBySource"
              :loading="isUpdatingBook"
            >
              执行书籍更新
            </Button>
          </p>
          <p class="find">
            书籍名
            <Input
              class="book-input"
              v-model="searchName"
              placeholder="请输入书籍名"
              clearable
            />
            作者
            <Input
              class="book-input"
              v-model="searchAuthor"
              placeholder="请输入作者名"
              clearable
            />
            公众号回复数字
            <Input
              class="book-input"
              style="width: 110px"
              v-model="searchSecret"
              placeholder="请输入回复数字"
              clearable
            />
            <Checkbox v-model="searchType" style="margin-right: 20px">
              只查找连载书籍
            </Checkbox>
            <Button type="primary" @click="findData">查询</Button>
          </p>
          <Table
            :columns="columnsList"
            :data="tableData"
            :loading="loading"
          ></Table>
          <Page
            class="pager"
            v-if="total > 0"
            :total="total"
            show-total
            show-elevator
            show-sizer
            :page-size="limit"
            :page-size-opts="[15, 30, 50, 100]"
            @on-change="handlePageChange"
            @on-page-size-change="handlePageSizeChange"
          ></Page>
        </Card>
        <!-- 新增和修改书籍弹窗 -->
        <Modal
          class="book-dialog"
          v-model="isShowModal"
          :title="modalTitle"
          :loading="modalLoading"
          @on-ok="handleModalConfrim"
          @on-cancel="handleModalCancel"
          width="600"
          :mask-closable="false"
        >
          <Form
            ref="modalForm"
            :model="modalData"
            :rules="modalRule"
            :label-width="100"
          >
            <FormItem prop="name" label="书籍名称" :error="modalError.name">
              <Input v-model="modalData.name" placeholder="请输入书籍名称" />
            </FormItem>
            <FormItem prop="author" label="作者" :error="modalError.author">
              <Input v-model="modalData.author" placeholder="请输入作者" />
            </FormItem>
            <FormItem
              prop="update_status"
              label="书籍状态"
              :error="modalError.update_status"
            >
              <i-select
                v-model="modalData.update_status"
                placeholder="请选择书籍状态"
              >
                <i-option value="全本">全本</i-option>
                <i-option value="已完结">已完结</i-option>
                <i-option value="连载中">连载中</i-option>
                <i-option value="暂停更新">暂停更新</i-option>
              </i-select>
            </FormItem>
            <FormItem prop="classify" label="分类" :error="modalError.classify">
              <i-select
                multiple
                v-model="modalData.classify"
                placeholder="请选择书籍分类"
              >
                <i-option v-for="item in classifys" :key="item" :value="item">{{
                  item
                }}</i-option>
              </i-select>
            </FormItem>
            <FormItem
              prop="newest_chapter"
              label="最新章节"
              :error="modalError.newest_chapter"
            >
              <Input
                v-model="modalData.newest_chapter"
                type="text"
                placeholder="请输入最新章节数"
              />
            </FormItem>
            <FormItem
              prop="hot_value"
              label="热度值"
              :error="modalError.hot_value"
            >
              <Input
                v-model="modalData.hot_value"
                type="text"
                placeholder="请输入热度值"
              />
            </FormItem>
            <FormItem
              prop="total_words"
              label="总字数"
              :error="modalError.total_words"
            >
              <Input
                v-model="modalData.total_words"
                type="text"
                placeholder="请输入总字数，比如100万字"
              />
            </FormItem>
            <FormItem
              prop="img_url"
              label="封面图片"
              :error="modalError.img_url"
            >
              <m-uploader
                :value.sync="modalData.img_url"
                :max-size="300 * 1024"
                desc="请上传347x150尺寸大小的图片，否则图片会自动放大来适配当前大小"
              />
            </FormItem>
            <FormItem prop="secret" label="秘钥" :error="modalError.secret">
              <Input
                class="secret-input"
                style="width: 300px; margin-right: 10px"
                v-model="modalData.secret"
                type="url"
                placeholder="请输入书籍秘钥"
              />
              <Button class="secret-btn" type="primary" @click="generateSecret"
                >生成秘钥</Button
              >
            </FormItem>
            <FormItem prop="des" label="书籍描述" :error="modalError.des">
              <Input
                v-model="modalData.des"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 5 }"
                placeholder="输入书籍描述"
                style="font-size: 12px"
              />
            </FormItem>
            <FormItem prop="source" label="书籍来源" :error="modalError.source">
              <template v-if="modalData.source.length > 0">
                <div v-for="(source, index) in modalData.source" :key="index">
                  <Input
                    v-model="modalData.source[index]"
                    placeholder="输入书籍来源"
                    style="font-size: 12px; width: 300px"
                  />
                  <i-button
                    type="primary"
                    size="small"
                    @click="makeTopBookSource(index)"
                    style="display: inline-block; vertical-align: middle"
                    >置顶</i-button
                  >
                  <i-button
                    type="error"
                    size="small"
                    @click="removeBookSource(index)"
                    style="display: inline-block; vertical-align: middle"
                    >删除</i-button
                  >
                </div>
              </template>
              <i-button
                type="primary"
                @click="addBookSource"
                :style="modalData.source.length > 0 ? 'margin-top: 10px' : ''"
                >添加书籍来源</i-button
              >
              <p style="margin-top: 10px; color: #808695; line-height: 1.5em">
                1. 设置书籍来源可以自动更新书籍
                <br />2. 排在上方的书籍来源在更新的时候有更高的优先级
              </p>
            </FormItem>
          </Form>
        </Modal>
        <Modal title="预览图片" v-model="previewImgVisable">
          <img
            :src="previewImgURL"
            v-if="previewImgVisable"
            style="
              width: auto;
              max-height: 200px;
              margin: 0 auto;
              display: block;
            "
          />
          <br />
          <br />
          <p>图片地址: {{ previewImgURL }}</p>
        </Modal>
      </i-col>
    </Row>
  </div>
</template>

<script>
import { oldHttp, baseURL } from '@/utils/http';
import moment from 'moment';
import Cookies from 'js-cookie';
import Uploader from '@/components/uploader';
import ImagePreview from '@/components/uploader/components/ImagePreview';

export default {
  name: 'theme',

  components: {
    [Uploader.name]: Uploader,
    [ImagePreview.name]: ImagePreview,
  },

  data() {
    return {
      loading: true,
      tableData: [],
      total: 0,
      page: 1,
      limit: 10,
      searchName: '', // 输入的需要搜索的书籍名
      searchAuthor: '', // 输入需要搜索的作者名
      searchSecret: '', // 输入公众号回复数字
      searchType: false, // 是否只查询连载中书籍
      classifys: [],
      columnsList: [
        {
          title: '序号',
          key: 'index',
          width: 60,
          minWidth: 60,
          align: 'center',
        },
        {
          title: '书籍名称',
          align: 'center',
          key: 'name',
          minWidth: 200,
          render: (h, params) => {
            return h('span', '《' + params.row.name + '》');
          },
        },
        {
          title: '书籍作者',
          align: 'center',
          key: 'author',
          minWidth: 150,
        },
        {
          title: '分类',
          align: 'center',
          key: 'classify',
          minWidth: 100,
          render: (h, params) => {
            if (
              params.row.classify instanceof Array &&
              params.row.classify.length > 0
            ) {
              return params.row.classify.map((item) => h('Tag', item));
            } else if (typeof params.row.classify === 'string') {
              return <Tag>{params.row.classify}</Tag>;
            } else {
              return <span>暂无</span>;
            }
          },
        },
        {
          title: '状态',
          align: 'center',
          key: 'update_status',
          minWidth: 80,
          render: (h, params) => {
            return h('span', params.row.update_status);
          },
        },
        {
          title: '热度值',
          align: 'center',
          key: 'hot_value',
          width: 80,
          minWidth: 80,
        },
        {
          title: '秘钥',
          align: 'center',
          key: 'secret',
          minWidth: 120,
        },
        {
          title: '更新时间',
          align: 'center',
          key: 'update_time',
          minWidth: 160,
          render: (h, params) => {
            return h(
              'span',
              params.row.update_time
                ? moment(params.row.update_time).format('YYYY/MM/DD HH:mm:ss')
                : '未知时间'
            );
          },
        },
        {
          title: '操作',
          align: 'center',
          width: 280,
          minWidth: 280,
          key: 'handle',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  class: 'change-btn',
                  props: {
                    type: 'primary',
                  },
                  on: {
                    click: () => {
                      // 打开修改弹窗
                      this.$router.push({
                        path: `/book-manage/${params.row._id}/chapter`,
                      });
                    },
                  },
                },
                '编辑章节'
              ),
              h(
                'Button',
                {
                  class: 'change-btn',
                  props: {
                    type: 'primary',
                  },
                  on: {
                    click: () => {
                      // 打开修改弹窗
                      this.modalData = {
                        name: params.row.name,
                        img_url: params.row.img_url,
                        author: params.row.author,
                        des: params.row.des,
                        classify: params.row.classify,
                        update_status: params.row.update_status,
                        newest_chapter: params.row.newest_chapter,
                        total_words: params.row.total_words,
                        hot_value: params.row.hot_value,
                        secret: params.row.secret,
                        source: params.row.source || [],
                      };
                      this.uploadFile = {
                        name: 'a42bdcc1178e62b4694c830f028db5c0',
                        url: params.row.img_url,
                      };
                      this.isShowModal = true;
                      this.modalTitle = '修改书籍';
                      this.isAddOrUpdateModal = 'update';
                      this.currentBookId = params.row._id;
                    },
                  },
                },
                '修改'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '温馨提示',
                        content: '确定要删除此书籍？',
                        onOk: () => {
                          oldHttp
                            .delete(
                              '/api/admin/book/' + params.row._id,
                              {},
                              '删除书籍'
                            )
                            .then((res) => {
                              if (res.data && res.data.ok) {
                                // 更新tableData
                                this.isShowModal = false;
                                this.$Message.success('删除书籍成功');
                                this.getData();
                              }
                            });
                        },
                        onCancel: () => {},
                      });
                    },
                  },
                },
                '删除'
              ),
            ]);
          },
        },
      ],
      hasDraged: false,
      isDraging: false, // 处在拖拽状态
      isShowModal: false, // 控制modal的显隐
      modalLoading: true, // 点击modal确定按钮是否显示loading
      modalTitle: '', // modal标题
      isAddOrUpdateModal: '', // 是新增弹窗或者更新弹窗
      currentBookId: '', // 当前正在修改的书籍Id
      modalData: {
        name: '',
        img_url: '',
        author: '',
        des: '',
        classify: [],
        update_status: '',
        newest_chapter: 0,
        total_words: '',
        hot_value: 0,
        secret: '',
        source: [],
      },
      modalRule: {
        name: [{ required: true, message: '请输入书籍名称', trigger: 'blur' }],
        author: [
          { required: true, message: '请输入作者名称', trigger: 'blur' },
        ],
        des: [{ required: true, message: '请输入书籍描述', trigger: 'blur' }],
        img_url: [
          { required: true, message: '请输入封面图片地址', trigger: 'blur' },
        ],
        newest_chapter: [],
        classify: [],
        update_status: [
          { required: true, message: '请选择书籍状态', trigger: 'blur' },
        ],
        hot_value: [],
        total_words: [],
        secret: [{ required: true, message: '请输入秘钥', trigger: 'blur' }],
        source: [],
      },
      modalError: {}, // modal错误提示信息
      isSyncMongo: false,
      isUpdatingBook: false,
      uploadFile: null, // 上传图片列表
      uploadToken: Cookies.get('mbook-admin-token'), // 上传需要携带的token信息
      uploadURL: baseURL + '/api/admin/upload-img', // 上传地址
      previewImgVisable: false, // 是否打开预览
      previewImgURL: '', // 预览图片地址
    };
  },
  methods: {
    getData() {
      let self = this;
      self.loading = true;
      if (self.searchName) {
        self.page = 1;
      }
      oldHttp
        .get(
          '/api/admin/book',
          {
            page: self.page,
            limit: self.limit,
            name: self.searchName,
            author: self.searchAuthor,
            status: self.searchType ? 1 : 0,
            secret: self.searchSecret,
          },
          '获取书籍列表'
        )
        .then((res) => {
          self.loading = false;
          if (res.ok) {
            self.tableData = res.list.map((item, index) => {
              item.index = (self.page - 1) * self.limit + index + 1;
              return item;
            });
            self.total = res.total;
            self.classifys = res.classify;
          }
        });
    },
    findData() {
      this.limit = 10;
      this.page = 1;
      this.total = 0;
      this.getData();
    },
    mongoSync() {
      let self = this;
      self.isSyncMongo = true;
      oldHttp
        .get('/api/mongosync', {}, '同步数据库到新书城', 30000)
        .then((res) => {
          self.isSyncMongo = false;
          if (res && res.ok) {
            this.$Notice.success({
              title: '温馨提示',
              desc: '同步成功',
            });
          }
        });
    },
    updateBookBySource() {
      let self = this;
      self.isUpdatingBook = true;
      this.$Notice.info({
        title: '温馨提示',
        desc: '书籍更新中，可能耗费比较长的时间，请稍后...',
      });
      oldHttp
        .get('/api/admin/update_book', {}, '手动执行书籍更新', 600000)
        .then((res) => {
          self.isUpdatingBook = false;
          if (res && res.ok && res.data) {
            this.$Notice.error({
              title: '温馨提示',
              desc: res.data,
            });
          }
        });
    },
    // 点击新增书籍
    handleAdd() {
      // 打开新增弹窗
      this.modalData = {
        name: '',
        img_url: '',
        author: '',
        des: '',
        classify: [],
        update_status: '',
        newest_chapter: '',
        total_words: '',
        hot_value: '',
        secret: '',
        source: [],
      };
      this.isShowModal = true;
      this.modalTitle = '新增书籍';
      this.isAddOrUpdateModal = 'add';
      this.uploadFile = null;
    },
    handleModalConfrim() {
      let self = this;
      // 合法性校验
      self.$refs['modalForm'].validate((valid) => {
        if (valid) {
          let isOk = true;
          let imgUrlRegExp = /^(http|https):\/\/.+\.(jpg|png|JPG|PNG|gif)$/;
          let httpUrlRegExp = /^(http|https):\/\/.+$/;
          let intergeRegExp = /^\d+$/;
          if (self.modalData.des.length > 200) {
            self.modalError.des = Math.random().toString();
            self.$nextTick(function () {
              self.modalError.des = '请输入0至200个字的书籍描述';
            });
            isOk = false;
          }
          if (
            !intergeRegExp.test(self.modalData.newest_chapter) ||
            self.modalData.newest_chapter < 0
          ) {
            self.modalError.newest_chapter = Math.random().toString();
            self.$nextTick(function () {
              self.modalError.newest_chapter = '请输入大于0的整数的章节数';
            });
            isOk = false;
          }
          if (
            !intergeRegExp.test(self.modalData.hot_value) &&
            self.modalData.hot_value < 0
          ) {
            self.modalError.hot_value = Math.random().toString();
            self.$nextTick(function () {
              self.modalError.hot_value = '请输入大于0的整数的热度值';
            });
            isOk = false;
          }
          self.modalData.source.forEach((source) => {
            if (!httpUrlRegExp.test(source)) {
              self.modalError.source = Math.random().toString();
              self.$nextTick(function () {
                self.modalError.source = '请输入正确书籍来源';
              });
              isOk = false;
            }
          });

          // 如果全部校验通过，发送POST请求
          if (isOk) {
            if (self.isAddOrUpdateModal === 'add') {
              oldHttp
                .post('/api/admin/book', self.modalData, '新增书籍')
                .then((res) => {
                  self.modalLoading = false;
                  // 避免校验完直接关闭弹窗
                  self.$nextTick(() => {
                    self.modalLoading = true;
                  });
                  if (res.ok) {
                    self.isShowModal = false;
                    self.$Message.success('新增书籍成功');
                    self.getData();
                  }
                })
                .catch((err) => {
                  self.modalLoading = false;
                  self.$nextTick(() => {
                    self.modalLoading = true;
                  });
                });
            } else if (self.isAddOrUpdateModal === 'update') {
              oldHttp
                .patch(
                  '/api/admin/book/' + self.currentBookId,
                  self.modalData,
                  '修改书籍'
                )
                .then((res) => {
                  self.modalLoading = false;
                  // 避免校验完直接关闭弹窗
                  self.$nextTick(() => {
                    self.modalLoading = true;
                  });
                  if (res.ok) {
                    self.isShowModal = false;
                    self.$Message.success('修改书籍成功');
                    self.getData();
                  }
                })
                .catch((err) => {
                  self.modalLoading = false;
                  self.$nextTick(() => {
                    self.modalLoading = true;
                  });
                });
            }
          } else {
            self.modalLoading = false;
            self.$nextTick(() => {
              self.modalLoading = true;
            });
          }
        } else {
          self.modalLoading = false;
          self.$nextTick(() => {
            self.modalLoading = true;
          });
        }
      });
    },
    handleModalCancel() {
      this.$refs['modalForm'].resetFields();
    },
    // 点击分页
    handlePageChange(val) {
      this.page = val;
      this.getData();
    },
    handlePageSizeChange(size) {
      this.limit = size;
      this.getData();
    },
    generateSecret() {
      this.modalData.secret = Math.random().toString().slice(-6);
    },
    addBookSource() {
      this.modalData.source.push('');
    },
    removeBookSource(index) {
      this.modalData.source.splice(index, 1);
    },
    makeTopBookSource(index) {
      let source = this.modalData.source[index];
      this.modalData.source.splice(index, 1);
      this.modalData.source.unshift(source);
    },
    // 上传图片相关
    handleImgView(url) {
      this.previewImgURL = url;
      this.previewImgVisable = true;
    },
    handleImgRemove(file) {
      this.uploadFile = null;
      // 重置img_url
      this.modalData.img_url = '';
    },
  },
  created() {
    this.getData();
  },
};
</script>

<style lang="scss">
.book-container .title {
  height: 32px;
  line-height: 32px;
}

.book-container .sync-btn {
  float: right;
  margin-right: 10px;
}
.book-container .add-icon {
  float: right;
}
.book-container .overflow-text {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.book-container .ivu-tooltip-inner {
  max-width: inherit;
}
.book-container .change-btn {
  margin-right: 15px;
}
.book-container .modal-container {
  width: 600px;
  position: absolute;
  left: 50%;
  top: 0;
  margin-left: -300px;
}
.book-container .book-input {
  display: inline-block;
  width: 200px;
  margin-left: 20px;
  margin-right: 20px;
}
.book-dialog textarea.ivu-Input {
  font-size: 12px !important;
}
.book-container .pager {
  text-align: right;
  margin-top: 30px;
}
.book-container .secret-btn {
  margin-left: 20px;
}
.book-container .secret-input {
  width: 300px;
}
.book-container .find {
  margin-bottom: 20px;
}
.book-container .find .right {
  float: right;
}
// 上传相关
.book-dialog .upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.book-dialog .upload-list img {
  width: 100%;
  height: 100%;
}
.book-dialog .upload-list .spin {
  line-height: 1.6;
}
.book-dialog .upload-list .spin-icon-load {
  animation: ani-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.book-dialog .upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.book-dialog .upload-list:hover .upload-list-cover {
  display: block;
}
.book-dialog .upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.book-dialog .ivu-modal-body {
  max-height: 600px;
  overflow: auto;
}
</style>
